package com.willie.redis.controller;

import com.willie.redis.entity.Student;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author willie
 * @since 2018/11/16
 */
@RestController
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/addStudent")
    public Boolean createStudent() {
        RLock rLock = redissonClient.getLock("aa");
        try {
            if (rLock.tryLock(0, 10, TimeUnit.SECONDS)) {
                redisTemplate.opsForHash().put("1", "1", new Student(1L,"阿呆",
                        18L));
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            rLock.unlock();
        }
        return false;
    }

    @GetMapping("/getStudent")
    public Student getStudent() {
        return (Student) redisTemplate.opsForHash().get("1", "1");
    }
}
